﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using umbraco.cms.businesslogic.web;
using umbraco.BusinessLogic;

namespace uREST.CMS.Util
{
    public class UmbracoHelper
    {
        public static List<Document> GetDocumentsByDocTypeAlias(string docTypeAlias, User user)
        {
            return GetDocumentsByDocTypeAlias(docTypeAlias, user.StartNodeId, user);
        }

        public static List<Document> GetDocumentsByDocTypeAlias(string docTypeAlias, int startNodeId, User user)
        {
            var docs = new List<Document>();

            if(user.StartNodeId > 0)
            {
                try
                {
                    var startNode = new Document(startNodeId);
                    if(!startNode.Path.Split(',').Contains(user.StartNodeId.ToString()))
                        startNodeId = user.StartNodeId;
                }
                catch { }
            }

            var sql = @"select id, path from umbracoNode
            inner join cmsContent on cmsContent.nodeId = umbracoNode.id 
            inner join cmsContentType on cmsContentType.nodeId = cmsContent.contentType 
            where cmsContentType.alias = '{0}' and path not like '%-20%' and path like '%{1}%'
            order by path";

            var startNodeParam = startNodeId != -1
                ? "," + startNodeId + ","
                : startNodeId + ",";

            sql = string.Format(sql, docTypeAlias, startNodeParam);

            var reader = umbraco.BusinessLogic.Application.SqlHelper.ExecuteReader(sql);

            while (reader.Read())
            {
                var docId = reader.GetInt("id");
                if (docId > 0)
                {
                    try
                    {
                        docs.Add(new Document(docId));
                    }
                    catch { }
                }
            }

            reader.Close();

            return docs;
        }
    }
}
